// metalUiAction.js
import { TestConfig } from "../common/testConfig.js";
import { TestSimulateData } from "../testMgr/testSimulateData.js";
import {
    getMetalRefiningContractData,
    getMetalRefiningDetailInfo,
    updateOrCreateMetalRefiningContract,
    reviewMetalRefiningOrder,
    withdrawReviewAndDeleteOrder,
    getMetalCombineData,
    updateOrCreateMetalCombineOrder,
    updateMetalCombineOrderBatch,
    getCustomersMetalBalanceData,
    getCombineOrderInOutStatic,
    getCurrentPeriodBalance,
    updateCustomerQuickExtention
} from "../../network/api.js";
import { ApiReturnStruct, getApiData, CommunicationPageData, NetworkParser } from "../../network/communicationConverter.js";
import { Engine } from "../engine.js";
import { DataPage } from "../../network/communicationConverter.js";
import { DocType } from '../common/docDefinition.js';
import { MetalRefiningContract } from "../metal/metalRefiningContract.js";
import { OrderResult } from "../common/orderResult.js";
import { MessageUtil } from '@/utils/MessageUtil.js';
import { ContractManufacturingStatus } from '../common/docDefinition.js';
import { MetalCombineOrder } from "../metal/metalCombineOrder.js";
import {TransactionBalance} from "../funds/transactionBalacne.js";
import { TargetObject } from "../targetOrg/targetObject.js";

/**
 * 金属委外加工单相关UI操作类
 */
export class MetalUiAction {
    /**
     * 获取金属委外加工单列表数据
     * @param {Object} options - 参数选项
     * @param {string} options.orgId - 组织ID
     * @param {DataPage} options.pageInfo - 分页信息
     * @param {Object} [options.filter] - 过滤条件
     * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
     * @returns {Promise<ApiReturnStruct>}
     */
    async getMetalRefiningContractData({
        orgId = null,
        pageInfo = null,
        filter = null,
        showLoadingPage = true
    }) {
        if (TestConfig.metalRefiningContractTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            if (filter != null && filter['b_orderStatus'] == null) {
                simData.dataList = testSimulateData.simStateMetalRefiningContractData(null);
            } else if (filter != null && filter['b_orderStatus'] === 0) {
                simData.dataList = testSimulateData.simStateMetalRefiningContractData(ContractManufacturingStatus.Working);
            } else if (filter != null && filter['b_orderStatus'] === 1) {
                simData.dataList = testSimulateData.simStateMetalRefiningContractData(ContractManufacturingStatus.Finished);
            } else {
                simData.dataList = testSimulateData.simStateMetalRefiningContractData(null);
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
            return await getApiData(
                MetalRefiningContract.fromJson,
                orgId,
                pageInfo,
                getMetalRefiningContractData,
                filter,
                showLoadingPage
            );
        }
    }

    /**
     * 获取金属委外加工单详情
     * @param {string} orderId - 加工单ID
     * @returns {Promise<MetalRefiningContract|null>}
     */
    async getMetalRefiningDetailInfo(orderId) {
        if (TestConfig.metalRefiningContractTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 模拟数据
            const testSimulateData = new TestSimulateData();
            let contractData = testSimulateData.simStateMetalRefiningContractData();

            // 查找匹配的元素
            let contract = contractData.find(item => item.id === orderId);
            if (contract) {
                return contract;
            }

            return testSimulateData.simStateMetalRefiningContractData()[0];
        } else {
            let res = await getMetalRefiningDetailInfo(orderId, Engine.profile.org.orgId);

            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, MetalRefiningContract.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * 创建或更新金属委外加工单
     * @param {MetalRefiningContract} contract - 加工单数据
     * @param {boolean} toAudit - 是否审核
     * @returns {Promise<OrderResult|null>}
     */
    async updateOrCreateMetalRefiningContract(contract, toAudit) {
        const res = await updateOrCreateMetalRefiningContract(contract, toAudit);

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * 审核金属委外加工单
     * @param {Array<string>} ids - 加工单ID列表
     * @param {string} orgId - 组织ID
     * @returns {Promise<any>}
     */
    async reviewMetalRefiningOrder(ids, orgId = null) {
        orgId = orgId ?? Engine.profile.org.orgId;

        const res = await reviewMetalRefiningOrder(ids, orgId);

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("审核委外加工单失败:" + apiResult.resErr);
            return apiResult;
        }

        return apiResult;
    }

    /**
     * 删除金属委外加工单
     * @param {Object} options - 参数选项
     * @param {string} options.orderId - 订单ID
     * @param {DocType} options.docType - 单据类型
     * @returns {Promise<any|null>}
     */
    async removeMetalRefiningOrder({
        orderId,
        docType
    }) {
        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除委外加工单据失败:" + apiResult.resErr);
            return apiResult;
        }

        return null;
    }

    /**
     * 显示金属委外加工单详情页面
     * @param {string} contractId - 加工单ID
     * @param {boolean} editMode - 是否编辑模式
     */
    async showMetalRefiningDetailPage(contractId, { editMode = false } = {}) {
        if (contractId) {
            uni.navigateTo({
                url: `/pages/manufactor/metalRefiningDetailPage?contractId=${contractId}&editMode=${editMode}`
            });
        } else {
            let store = Engine.profile?.getValideStore;
            let storeParam = "";
            if (store) {
                storeParam = "&storeId=" + store.id + "&storeName=" + store.name;
            }

            uni.navigateTo({
                url: `/pages/manufactor/metalRefiningDetailPage?editMode=${editMode}` + storeParam
            });
        }
    }

    /**
 * 获取金属综合单据列表数据
 * @param {Object} options - 参数选项
 * @param {string} options.orgId - 组织ID
 * @param {DataPage} options.pageInfo - 分页信息
 * @param {Object} [options.filter] - 过滤条件
 * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
 * @returns {Promise<ApiReturnStruct>}
 */
    async getMetalCombineData({
        orgId = null,
        pageInfo = null,
        filter = null,
        showLoadingPage = true
    }) {

        if (TestConfig.metalMetalCombineOrderTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            simData.dataList = testSimulateData.simMetalCombineOrder();

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
            return await getApiData(
                MetalCombineOrder.fromJson,
                orgId,
                pageInfo,
                getMetalCombineData,
                filter,
                showLoadingPage
            );
        }
    }

    /**
     * 创建或更新金属综合单据
     * @param {MetalCombineOrder} order - 综合单据数据
     * @param {boolean} toAudit - 是否审核
     * @returns {Promise<OrderResult|null>}
     */
    async updateOrCreateMetalCombineOrder(order, toAudit) {
        const res = await updateOrCreateMetalCombineOrder(order, toAudit);

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * 批量更新金属综合单据
     */
    async updateMetalCombineOrderBatch(param) {
        let orgId = Engine.profile.org.orgId;

        const res = await updateMetalCombineOrderBatch({
            param: param,
            orgId: orgId
        });

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);


        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg(apiResult.resErr);
            return null;
        }
        else {
            return apiResult;
        }

    }



    /**
     * 删除金属综合单据
     * @param {Object} options - 参数选项
     * @param {string} options.orderId - 订单ID
     * @param {DocType} options.docType - 单据类型
     * @returns {Promise<any|null>}
     */
    async removeMetalCombineOrder({
        orderId,
        docType
    }) {
        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除金属综合单据失败:" + apiResult.resErr);
            return apiResult;
        }

        return null;
    }


       /**
 * 贵金属客户结算列表
 * @param {Object} options - 参数选项
 * @param {string} options.orgId - 组织ID
 * @param {DataPage} options.pageInfo - 分页信息
 * @param {Object} [options.filter] - 过滤条件
 * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
 * @returns {Promise<ApiReturnStruct>}
 */
    async getCustomersMetalBalanceData({
        orgId = null,
        pageInfo = null,
        filter = null,
        showLoadingPage = true
    }) {

        if (TestConfig.metalMetalCombineOrderTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            simData.dataList = testSimulateData.simCustomersMetalBalances();

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
            return await getApiData(
                TargetObject.fromJson_ForTrasitionBalance,
                orgId,
                pageInfo,
                getCustomersMetalBalanceData,
                filter,
                showLoadingPage
            );
        }
    }


       /**
 * 获取统计当日，昨日，本月营收，贵金属回收销售
 * @param {Object} options - 参数选项
 * @param {string} options.orgId - 组织ID
 * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
 * @returns {[MetalCombineOrder]}
 */
    async getCombineOrderInOutStatic({
        orgId = null,   
        showLoadingPage = true
    }) {

        if (TestConfig.metalMetalCombineOrderTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));
        
            let ret = new ApiReturnStruct();
            ret.data =  testSimulateData.simMetalCombineOrder();

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
                 let res = await getCombineOrderInOutStatic({orgId:Engine.profile.org.orgId});

            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, MetalCombineOrder.fromJson,{ isListData:true });

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

/**
 * 查询当前存欠款和存欠料数据
 * @param {Object} options - 参数选项
 * @param {string} options.orgId - 组织ID
 * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
 * @returns {MetalCombineOrder}
 */
    async getCurrentPeriodBalance({
        orgId = null,   
        showLoadingPage = true
    }) {

        if (TestConfig.metalMetalCombineOrderTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));
        
            let ret = new ApiReturnStruct();
            ret.data =  testSimulateData.simMetalCombineOrder();

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
                 let res = await getCurrentPeriodBalance({orgId:Engine.profile.org.orgId});

            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, MetalCombineOrder.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * 更新UI配置参数
     * @param {Object} options - 参数选项
     * @param {string} options.orgId - 组织ID
     * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
     * @returns {MetalCombineOrder}
     */
    /**
     * 更新客户金属显示列
     */
    async updateCustomerMetalCombineFilesShowConfig(customer, metalCombineFilesShowConfig) {
        let orgId = Engine.profile.org.orgId;

        let quickExtentionFields = customer.quickExtentionFields ?? {};
        quickExtentionFields.metalCombineFilesShowConfig = metalCombineFilesShowConfig;

                

        const res = await updateCustomerQuickExtention({
            id: customer.id,
            orgId: orgId,
            quickExtentionFields: JSON.stringify(quickExtentionFields) // quickExtentionFields 转换为 string
        });

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);


        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg(apiResult.resErr);
            return null;
        }
        else {
            return apiResult;
        }

    }

}